package routehb

import (
	"fmt"
	"gitee.com/gitee-go/core"
	"gitee.com/gitee-go/server/comm"
	"gitee.com/gitee-go/utils"
	hbtp "github.com/mgr9525/HyperByte-Transfer-Protocol"
	"time"
)

/**
runner 调用 server 的函数,需要附带签名确认安全
*/
func servAuthToken(c *hbtp.Context) bool {
	defer func() {
		if err := recover(); err != nil {
			c.ResString(hbtp.ResStatusAuth, fmt.Sprintf("auth recover err:%v", err))
		}
	}()
	hd, err := c.ReqHeader()
	if err != nil {
		c.ResString(hbtp.ResStatusAuth, "auth head err:"+err.Error())
		return false
	}
	token := utils.Md5String(hd.Path + hd.RelIp + hd.Times + comm.MainCfg.RunnerConf.Secret)
	if hd.Token != token {
		core.Log.Error("token err:" + hd.Token)
		c.ResString(hbtp.ResStatusAuth, "auth token err:"+hd.Token)
		return false
	}
	tms, err := time.Parse(time.RFC3339Nano, hd.Times)
	if err != nil {
		c.ResString(hbtp.ResStatusAuth, "auth times err:"+err.Error())
		return false
	}
	tms = tms.Local()
	if time.Since(tms).Minutes() > 5 {
		c.ResString(hbtp.ResStatusAuth, "auth time out:"+tms.String())
		return false
	}
	//logrus.Info("ruisAuthToken header.times:" + hd.Times)
	//core.Log.Info(fmt.Sprintf("ruisAuthToken(%d:%s) parse.times:%s", c.Code(), hd.Path, tms.Format(common.TimeFmt)))
	//logrus.Info("ruisAuthToken parse.times.local:" + tms.In(time.Local).Format(comm.TimeFmt))
	return true
}
